<template>
  <div class="map-container">
    <div class="map-header">
      <h2>去过的城市</h2>
    </div>
    <div id="gd-map" class="gd-map"></div>
    <div class="marker-info" v-if="selectedMarker">
      <h3>标记信息</h3>
      <p>位置: {{ selectedMarker.position }}</p>
      <p>描述: {{ selectedMarker.description }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MapModule',
  data() {
    return {
      map: null,
      markers: [],
      selectedMarker: null,
      animationId: null,
      mapData: {
        center: [115.858198, 28.682892], 
        zoom: 6,
        markers: [
          {
            id: 1,
            position: [115.858198, 28.682892],
            description: '南昌'
          },
          {
            id: 2,
            position: [118.796877, 32.060255],
            description: '南京'
          },
          {
            id: 3,
            position: [118.089475, 24.479298],
            description: '厦门'
          },
          {
            id: 4,
            position: [117.184811, 34.261792],
            description: '徐州'
          }
        ]
      },
      lines: []
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.loadAMapScript().then(() => {
        this.map = new AMap.Map('gd-map', {
          zoom: this.mapData.zoom,
          center: this.mapData.center
        });
        
        this.addDefaultMarkers();
      }).catch(error => {
        console.error('地图加载失败:', error);
      });
    },
    
    loadAMapScript() {
      return new Promise((resolve, reject) => {
        if (window.AMap) {
          resolve();
          return;
        }
        
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=YOUR_AMAP_KEY&callback=onAMapLoaded';
        script.onerror = reject;
        
        window.onAMapLoaded = () => {
          resolve();
        };
        
        document.head.appendChild(script);
      });
    },
    
    addDefaultMarkers() {
      this.lines.forEach(line => line.setMap(null));
      this.lines = [];
      
      this.mapData.markers.forEach(markerData => {
        const marker = new AMap.Marker({
          position: markerData.position,
          title: markerData.description
        });
        
        marker.on('click', () => {
          this.selectedMarker = markerData;
          const infoWindow = new AMap.InfoWindow({
            content: `<div><strong>${markerData.description}</strong><br>位置: ${markerData.position.join(', ')}</div>`,
            offset: new AMap.Pixel(0, -30)
          });
          infoWindow.open(this.map, marker.getPosition());
        });
        
        marker.setMap(this.map);
        this.markers.push(marker);
      });
      
      // 添加3D效果的动态连线
      const nanchangPosition = this.mapData.markers[0].position;
      for (let i = 1; i < this.mapData.markers.length; i++) {
        // 创建3D效果的贝塞尔曲线路径
        const targetPosition = this.mapData.markers[i].position;
        const midPoint = [
          (nanchangPosition[0] + targetPosition[0]) / 2,
          (nanchangPosition[1] + targetPosition[1]) / 2
        ];
        
        // 计算控制点，创建弧线效果
        const controlPoint = [
          midPoint[0],
          midPoint[1] + 2 // 增加纬度偏移创建3D弧线效果
        ];
        
        // 创建动态动画效果
        this.createAnimatedLine(nanchangPosition, controlPoint, targetPosition);
      }
    },
    
    // 创建带动画效果的3D连线
    createAnimatedLine(start, control, end) {
      // 创建贝塞尔曲线路径
      const path = [];
      const steps = 100;
      
      for (let i = 0; i <= steps; i++) {
        const t = i / steps;
        // 二次贝塞尔曲线公式
        const x = (1 - t) * (1 - t) * start[0] + 2 * (1 - t) * t * control[0] + t * t * end[0];
        const y = (1 - t) * (1 - t) * start[1] + 2 * (1 - t) * t * control[1] + t * t * end[1];
        path.push([x, y]);
      }
      
      // 创建动态流动效果
      let flowLine = new AMap.Polyline({
        path: path,
        strokeColor: '#3366FF',
        strokeWeight: 2,
        strokeOpacity: 0.8,
        lineCap: 'round',
        zIndex: 50
      });
      
      flowLine.setMap(this.map);
      this.lines.push(flowLine);
      
      // 添加动态流动效果
      this.animateLine(flowLine, path);
    },
    
    // 实现线条流动动画
    animateLine(line, path) {
      let index = 0;
      const total = path.length;
      
      const animate = () => {
        if (!this.map) return;
        
        // 创建流动效果，只显示路径的一部分
        const visiblePath = path.slice(0, index);
        line.setPath(visiblePath);
        
        index += 3; // 控制动画速度
        
        if (index < total + 10) { // 留一些余量确保完整显示
          this.animationId = requestAnimationFrame(animate);
        } else {
          // 动画完成后显示完整路径
          line.setPath(path);
          
          // 添加脉冲效果
          this.pulseLine(line);
        }
      };
      
      this.animationId = requestAnimationFrame(animate);
    },
    
    // 实现线条脉冲效果
    pulseLine(line) {
      let opacity = 0.8;
      let direction = -0.02;
      
      const pulse = () => {
        if (!this.map) return;
        
        opacity += direction;
        if (opacity <= 0.3) {
          direction = 0.02;
        } else if (opacity >= 0.8) {
          direction = -0.02;
        }
        
        line.setOptions({
          strokeOpacity: opacity
        });
        
        // 持续脉冲效果
        this.animationId = requestAnimationFrame(pulse);
      };
      
      this.animationId = requestAnimationFrame(pulse);
    },
    
    addMarker() {
      if (!this.map) return;
      
      const center = this.map.getCenter();
      const marker = new AMap.Marker({
        position: [center.lng, center.lat],
        title: '新标记点'
      });
      
      marker.setMap(this.map);
      this.markers.push(marker);
      
      marker.on('click', () => {
        this.selectedMarker = {
          position: [center.lng, center.lat],
          description: '用户添加的标记点'
        };
      });
    },
    
    clearMarkers() {
      this.markers.forEach(marker => {
        marker.setMap(null);
      });
      this.markers = [];
      this.selectedMarker = null;
      
      // 清理连线动画
      this.lines.forEach(line => {
        line.setMap(null);
      });
      this.lines = [];
    },

  },
  beforeUnmount() {
    // 清理地图实例
    if (this.map) {
      this.map.destroy();
    }
    
    // 清理连线
    this.lines.forEach(line => {
      line.setMap(null);
    });
    this.lines = [];
    
    // 清理动画
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
  }
};
</script>

<style scoped>
.map-container {
  background: #333;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  height: 600px;
  display: flex;
  flex-direction: column;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  color: #e0e0e0;
  flex-wrap: wrap;
}

.map-header h2 {
  margin: 0;
}

.controls {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.controls button {
  background: #555;
  color: #fff;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.controls button:hover {
  background: #777;
}

.gd-map {
  flex: 1;
  border: 1px solid #444;
  border-radius: 4px;
  overflow: hidden;
}

.marker-info {
  margin-top: 15px;
  padding: 15px;
  background: #444;
  border-radius: 4px;
  color: #e0e0e0;
}

.marker-info h3 {
  margin-top: 0;
}
</style>